const fs = require("fs");
const path = require("path");

/**
 * @param dirList {Array} 文件夹名称
 * @description 判断是文件夹还是文件
 * @returns {Boolean} true:文件夹/false文件
 */
const fsType = (dirList = [], basePath) => {
  const reslover = {
    dir: [],
    file: [],
  };
  dirList.forEach((item) => {
    const currentFileStat = fs.statSync(
      path.resolve(__dirname, basePath + "/" + item)
    );
    const isDir = currentFileStat.isDirectory();
    isDir ? reslover.dir.push(item) : reslover.file.push(item);
  });
  return reslover;
};

/**
 * @description 获取src下面所有的文件
 * @returns {Object} {"@assets":"D:\vite\viite-space\src\assets"}
 */
const getAllFileToSrc = (preFix = "@", basePath = "../src") => {
  const filePath = fs.readdirSync(path.resolve(__dirname, basePath));
  const reslover = fsType(filePath, basePath);
  const resloverAlias = {};
  reslover.dir.forEach((item) => {
    resloverAlias[preFix + item] = path.resolve(
      __dirname,
      basePath + "/" + item
    );
  });
  console.log(resloverAlias)
  return resloverAlias
};

/**
 *
 * @config {function} vite固定写法
 *
 * @param { vite } /vite.confiig.js的配置config/env表示环境
 */
module.exports = (
  {
    prefix,
    basePath
  }
) => {
  return {
    config(config, env) {
      const resloverAlias = getAllFileToSrc(prefix,basePath);
      return {
        resolve: {
          alias: resloverAlias,
        },
      };
    },
  };
};

